

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import modelo.Game;
import constants.Constants;
import constants.Parameters;
import constants.ReadFromParametersXML;
import controller.ClientHandler;
import controller.Controller;
import controller.Server;

/**
 * this is the main class of the program that will launch de app 
 * it will connect to the client if it is ready for play and will start a new game
 * @author Jose Luis Garcia && Alvaro Blazquez Checa
 *
 */
public class Main {

	private static boolean exitProgram = false;
	
	public static void main(String[] args) {
		
		try {
			ReadFromParametersXML reader = new ReadFromParametersXML(Constants.PARAMETERS_FILE);
			Parameters.createParameters(reader.getIp(), reader.getPort(), reader.getMaxPlayers(), reader.getMinPlayers(), reader.getMaxMoves());
		} catch (ParserConfigurationException | SAXException | IOException e) {
			Parameters.createParameters(Constants.IP, Constants.PORT, Constants.MAX_PLAYERS, Constants.MIN_PLAYERS, Constants.MAX_MOVES);
		}
		Server server = new Server(Parameters.getInstance().PORT);
		new Thread(server).start();
		
		while(!exitProgram){
			
			try {
				Thread.sleep(Constants.WAIT_TIME_FOR_START);
			} catch (InterruptedException e) {
				System.out.println(e);
			}
			
			if(ClientHandler.clientList.size() >= Parameters.getInstance().MIN_PLAYERS){
				Controller controller = Controller.createController(Game.createGame());
				Game.getInstance().addListener(controller);
				controller.startGame();

				for(ClientHandler client : ClientHandler.clientList){
					client.disconnect();
				}
			}
		}
	}
	/**
	 * to close the program
	 */
	public static void exitProgram(){
		exitProgram = true;
	}
	
}
